<script lang="ts" setup>
import { Button, Tab, Tabs, showConfirmDialog, showDialog, showFailToast, showSuccessToast } from 'vant'
import lodash from 'lodash'
import { ContactApi } from '~/api/ContactApi'
import { JobRecordApi } from '~/api/JobRecordApi'
import { OrderApi } from '~/api/OrderApi'
import ContactAvatar from '~/components/contact/ContactAvatar.vue'
import BriefTableOfConsumer from '~/components/order/BriefTableOfConsumer.vue'
import type { ContactModel } from '~/model'

const id = ref(-1)
const route = useRoute()
const router = useRouter()
const contact = ref(null as ContactModel | null)
const tabIndex = useSessionStorage('contact-detail-tabindex', 0)

const noteTemplate = `1. 惯用别名
无
(例如：小筐子指的是2Kg黄T，4Kg筐指的是黄多柱)

2. 选择偏好
无
(例如：小保鲜纸必须用鲜峰的，大保鲜纸必须用常青的等)

3. 用户价格
默认价格，特殊待遇必须记录
(例如：2Kg梯形筐(黄色) 2.3元)

4. 结账方式
默认是先付款再放行，特殊情况必须记录
(例如：先放行，再通知经理收款)
(例如：不负责收款)
`

function clickDelete() {
  showConfirmDialog({
    message: `你确定要删除用户 “${contact.value?.name}” 吗?`,
  })
    .then(() => {
      handleDelete()
    })
}

async function handleDelete() {
  if (contact.value === null)
    return

  // 检查是否有订单
  // const allOrder = await OrderApi.getAll()
  // if (allOrder.find(order => order.consumer?.id === contact.value?.id)) {
  //   showFailToast('不能删除有过账目的用户')
  //   return
  // }

  // 检查是否工作过
  // const allJobRecord = await JobRecordApi.getAll()
  // if (allJobRecord.find(jr => jr.worker?.id === contact.value?.id)) {
  //   showFailToast('不能删除在职或者离职员工')
  //   return
  // }

  const result = await ContactApi.remove(contact.value.id)
  if (result.success) {
    router.back()
  }
  else {
    showDialog({
      message: result.message ?? '删除失败。有订单的用户无法删除，如果该用户没有订单，请联系管理员',
    }).then(() => {
      // on close
    })
  }
}

// edit
async function handleEdit() {
  if (!contact.value) {
    return
  }
  router.push(`/contacts/edit?id=${contact.value.id}`)
}

onMounted(async () => {
  const _id = route.query.id as (string | undefined)
  if (!_id) {
    return
  }
  id.value = Number.parseInt(_id)
  const allContact = await ContactApi.getAll()
  const _contact = allContact.find(x => x.id === id.value) || null
  contact.value = lodash.cloneDeep(_contact)
})

function phoneCall() {
  window.location.href = `tel:${contact.value?.phone}`
}

function onNewOrder() {
  router.push(`/orders/edit?user=${contact.value?.id}`)
}

function onAllOrder() {
  router.push(`/orders?user=${contact.value?.id}`)
}

async function onNoteCreate() {
  if (!contact.value) {
    return
  }
  contact.value.notes = noteTemplate
  const ok = await ContactApi.update(contact.value.id, contact.value)
  if (ok) {
    showSuccessToast('创建成功')
  }
}

setTimeout(() => {
  console.log(contact.value?.notes)
}, 1000)
</script>

<template>
  <div>
    <div v-if="!contact" m2 paper>
      加载中...
    </div>
    <div v-else>
      <ContactAvatar :contact="contact" :size="32" :can-click="true" :can-unload="false" mx-auto mb2 />
      <div text-center text-size-6>
        {{ contact.name }}
      </div>
      <div mb2 text-center text-size-3.5 text-gray-4>
        {{ contact.phone }}
      </div>

      <div mb2 flex text-size-3.5>
        <div mb0 mr2 paper flex flex-1 flex-col items-center p5 @click="onNewOrder">
          <font-awesome-icon h-7 c-purple-600 :icon="['fas', 'file-circle-plus']" />
          <div mt2 text-gray>
            新订单
          </div>
        </div>
        <!-- <div mb0 mr2 paper flex flex-1 flex-col items-center p5 @click="onAllOrder">
          <font-awesome-icon h-7 c-blue-600 :icon="['fas', 'book']" />
          <div mt2 text-gray>
            所有订单
          </div>
        </div> -->
        <div mb0 paper flex flex-1 flex-col items-center p5 @click="phoneCall">
          <font-awesome-icon h-7 c-green-600 :icon="['fas', 'phone']" />
          <div mt2 text-gray>
            拨号
          </div>
        </div>
      </div>

      <div mb flex text-size-3.5>
        <div mb0 mr2 paper flex flex-1 flex-col items-center p2 @click="handleEdit">
          <font-awesome-icon h-6 c-orange-600 :icon="['fas', 'pen-to-square']" />
          <div mt1 text-gray>
            修改
          </div>
        </div>
        <div mb0 paper flex flex-1 flex-col items-center bg-rose-600 p2 @click="clickDelete">
          <font-awesome-icon h-6 c-white :icon="['fas', 'trash-can']" />
          <div mt1 text-white>
            删除
          </div>
        </div>
      </div>

      <Tabs v-model:active="tabIndex" paper of-hidden p0>
        <Tab title="订单">
          <BriefTableOfConsumer :contact="contact" />
          <div h-12 flex items-center justify-center text-blue-600 @click="onAllOrder">
            查看所有
          </div>
        </Tab>
        <Tab title="档案">
          <div paper :style="{ whiteSpace: 'pre-line' }">
            {{ contact.notes }}
          </div>
          <!-- <Button v-if="contact.notes" square type="primary" w-full @click="onNoteModify">
            修改
          </Button> -->
          <Button v-if="!contact.notes" square type="primary" w-full @click="onNoteCreate">
            创建(销售经理模板)
          </Button>
        </Tab>
      </Tabs>
    </div>
  </div>
</template>

<style scoped>

</style>

<route lang="yaml">
meta:
  title: 联系人
</route>
